﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using iRealtor.Maps.Core.Entities;
using iRealtor.Maps.Core.Helpers;
using iRealtor.Maps.DataAccess.Models;
using iRealtor.Maps.DataAccess.Services;

namespace iRealtor.Maps.Core.Services
{
	public class PlacesService : MySQLBaseService
	{
		public List<PlaceView> GetPlaces()
		{
			var views = new List<PlaceView>();

			var places = GetPlacesInternal();
			var images = GetPlaceImages();

			foreach (var place in places)
			{
				var view = new PlaceView
							{
								Place = place,
								PlaceImages = images.Where(p => p.PlaceId == place.PlaceId).ToList()
							};

				views.Add(view);
			}

			return views;
		}

		public void AddNewPlace(Place place)
		{
			this.Save(place);
		}

		#region Helpers

		private IEnumerable<Place> GetPlacesInternal()
		{
			var q = new MySqlCommand("select * from Places");

			var places = dao.Load<Place>(q).ToList();
			return places;
		}

		private List<PlaceImage> GetPlaceImages()
		{
			var q = new MySqlCommand("select pi.* from PlaceImages pi inner join Places p on p.PlaceId = pi.PlaceId");
			var images = dao.Load<PlaceImage>(q).ToList();

			return images;
		}

		#endregion
	}
}
